﻿using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mayn.Video
{

    public static class MemoryShare
    {
        private const string memoryName = "MaynShareMemory";

        public static void WriteMsg(string msg)
        {
            // 创建或打开共享内存
            using (MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateOrOpen(memoryName, 500))
            {
                // 将文本转换为字节数组
                byte[] data = Encoding.UTF8.GetBytes(msg);

                // 在共享内存中写入数据
                using (MemoryMappedViewStream stream = memoryMappedFile.CreateViewStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
        }


        /// <summary>
        /// 读取消息
        /// </summary>
        /// <param name="delOld"></param>
        public static string ReadMsg(bool delOld = true)
        {
            string msg = "";

            try
            {
                // 打开已创建的共享内存
                var memoryMappedFile = MemoryMappedFile.OpenExisting(memoryName);

                // 从共享内存中读取数据
                using (MemoryMappedViewStream stream = memoryMappedFile.CreateViewStream())
                {
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);

                    // 去除末尾的空字符
                    int nullTerminatorIndex = Array.IndexOf(buffer, (byte)0);
                    string data = nullTerminatorIndex >= 0
                        ? Encoding.UTF8.GetString(buffer, 0, nullTerminatorIndex)
                        : Encoding.UTF8.GetString(buffer);
                    if (!string.IsNullOrEmpty(data))
                    {
                        msg = data;
                    }
                }

                if (delOld)
                {
                    // 删除共享内存中的消息
                    using (MemoryMappedViewAccessor accessor = memoryMappedFile.CreateViewAccessor())
                    {
                        // 将共享内存设置为空数据或null
                        byte[] emptyData = new byte[accessor.Capacity];
                        accessor.WriteArray(0, emptyData, 0, emptyData.Length);
                    }
                }

                // 关闭共享内存
                memoryMappedFile.Dispose();
            }
            catch (Exception ex)
            {
                
            }

            return msg;
        }
    }
}
